<?php
/**
 * 运营问答管理
 * @author      futao
 * @date        2016-1-16
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */

namespace Apps\Manage\Controllers;


use Apps\Common\Models\Question;
use Apps\Common\Models\QuestionAnswer;
use Apps\Common\Models\SysOpenCity;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\UserBase;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\QuestionAnswerComments;
use Apps\Common\Models\QuestionViewsUser;


class QuestionmanageController extends BaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('question');
    }
    /**
     * 开通的城市
     * @return \Phalcon\Mvc\Model\Criteria
     */
    private function openCityList()
    {
    	return SysOpenCity::find();
    }
    /**
     * 问答详情
     * @date: 2016-1-16 
     * @author: futao
     */
    public function infoAction(){
    	$this->setLeftNav("info");
    	$req=$this->request;	
    	$questionId = intval($req->getQuery('id',null,0));
    	if($questionId<0){
    		echo "参数错误！";
    		return;
    	}
    	$questionColumns=[
			'ub.user_id',
			'ub.user_nickname',
			'ub.user_cover',
			'Apps\Common\Models\Question.user_id',
			'Apps\Common\Models\Question.question_content',
			'Apps\Common\Models\Question.question_pics',
			'Apps\Common\Models\Question.question_addtime',
			'Apps\Common\Models\Question.question_browsers',
			'Apps\Common\Models\Question.question_id'
    	];
    	$info = Question::query()
    	->columns($questionColumns)
    	->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\Question.user_id', 'ub')
    	->where("Apps\Common\Models\Question.question_id = $questionId and Apps\Common\Models\Question.question_state = 1")
    	->execute()->getFirst();
    	if(!$info){
    		echo "问题不存在！";
    		exit;
    	}
    	$info->user_cover = PicUrl::UserCover($info->user_cover,$this->di);
    	if(unserialize(base64_decode($info->question_content))){
    		$info->question_content = unserialize(base64_decode($info->question_content));
    	}
    	if(json_decode($info->question_pics)){
    		$info->question_pics = json_decode($info->question_pics);
    	}
    	$answerColumns=[
			'ub.user_nickname',
			'ub.user_cover',
			'Apps\Common\Models\QuestionAnswer.answer_content',
			'Apps\Common\Models\QuestionAnswer.answer_addtime',
			'Apps\Common\Models\QuestionAnswer.answer_id',
			'Apps\Common\Models\QuestionAnswer.original_content',
			'Apps\Common\Models\QuestionAnswer.answer_pics',
			'Apps\Common\Models\QuestionAnswer.type',
			'Apps\Common\Models\QuestionAnswer.user_id'
    	];
    	$answerList = QuestionAnswer::query()
    		->columns($answerColumns)
    		->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\QuestionAnswer.user_id', 'ub')
    		->where("Apps\Common\Models\QuestionAnswer.question_id = $questionId and Apps\Common\Models\QuestionAnswer.answer_state = 1")
    		->orderBy("Apps\Common\Models\QuestionAnswer.answer_addtime desc")
    		->execute()->toArray();
    	foreach ($answerList as $k=>$val){
    		if(unserialize(base64_decode($answerList[$k]['answer_content']))){
    			$answerList[$k]['answer_content']=unserialize(base64_decode($answerList[$k]['answer_content']));
    		}	
    		if(unserialize(base64_decode($answerList[$k]['original_content']))){
    			$answerList[$k]['original_content']=unserialize(base64_decode($answerList[$k]['original_content']));
    		}
    		if(json_decode($answerList[$k]['answer_pics'])){
    			$answerList[$k]['answer_pics'] = json_decode($answerList[$k]['answer_pics']);
    		}
    		if($answerList[$k]['type']==2){
    			$answerList[$k]['reply']=QuestionAnswerComments::query()
    				->columns([
						'ub.user_nickname',
    					'ub.user_cover',
                        'ub.user_id',
    					'content',
    					'add_time',
    					'id',
                        'answer_id'
    				])
    				->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\QuestionAnswerComments.user_id', 'ub')
    				->where("question_id = $questionId and answer_id = ".$answerList[$k]['answer_id'])
    				->orderBy("add_time asc")
    				->execute()->toArray();
                foreach($answerList[$k]['reply'] as $key=>$v){
                    if(unserialize(base64_decode($answerList[$k]['reply'][$key]['content']))){
                        $answerList[$k]['reply'][$key]['content']=unserialize(base64_decode($answerList[$k]['reply'][$key]['content']));
                    }
                }
    		}
    		$answerList[$k]['user_cover'] = PicUrl::UserCover($answerList[$k]['user_cover'], $this->di);
    	}
    	$userList=UserBase::find("is_manage = 1");
    	
    	$seeList = QuestionViewsUser::query()
    		->columns([
    		    'distinct ub.user_id',
				'ub.user_cover'
    		])
    		->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\QuestionViewsUser.user_id', 'ub')
    		->where("question_id = $questionId")
    		->orderBy("id desc")
    		->limit(7)
    		->execute();
    	$this->view->setVar('seelist',$seeList);
    	$this->view->setVar('comment_count' , QuestionAnswer::count('answer_state = 1 and question_id = '.$questionId));
    	$this->view->setVar('question_id',$questionId);
    	$this->view->setVar('userlist',$userList);
    	$this->view->setVar('questioninfo',$info);
    	$this->view->setVar('answerlist',$answerList);
    	$this->view->pick('question/info');
    }
    /**
     *  回答问题
     * @date: 2016-1-16 
     * @author: futao
     */
    public function addanswerAction()
    {
        $this->view->disable();
        $req = $this->request;
        $type = $req->getPost('type', null, 0);//1：回复楼主    3：回复网友
        $userId = intval($req->getPost('user_id', null, 0));
        $answerId = intval($req->getPost('answer', null, 0));
        $questionId = intval($req->getPost('question_id', null, 0));
        $content = $req->getPost('content', null, '');
        $toUserid = $req->getPost('to_user_id',null,'');
        $echo = function ($msg, $state = false) {
            echo '<script type="text/javascript">';
            echo 'parent.formResult("' . $msg . '", ' . ($state ? 1 : 0) . ')';
            echo '</script>';
        };
        if ($type == 3) {
            if ($answerId < 0) {
                $echo("参数错误！");
                return;
            }
        }
        if ($questionId < 0 || $userId < 0) {
            $echo('参数错误！');
            return;
        }
        $floor = QuestionAnswer::query()->where("question_id = $questionId")->orderBy("answer_id desc")->execute()->getFirst();
        if (!$floor) {
            $floor = json_encode(['answer_floor' => 0]);
        }
        $uploadModel = new UploadPic();
        $uploadModel->request = $req;
        $picArr = $uploadModel->questionPic();
        $userInfo = UserBase::query()->where("user_id = {$userId}")->execute()->getFirst();
        if (!$userInfo) {
            $echo('参数错误！');
            return;
        }
        if ($userInfo->user_expert == 1) {
            $this->di['db']->Query('update question set question_browsers = question_browsers + 1 , answer_num = answer_num + 1 , is_expert_reply = 1 where question_id = ' . $questionId);
        } else {
            $this->di['db']->Query('update question set question_browsers = question_browsers + 1 , answer_num = answer_num + 1 where question_id = ' . $questionId);
        }
    	$question = new QuestionViewsUser();
    	$question->question_id = $questionId;
    	$question->user_id = $userId;
    	$question->add_time = date("Y-m-d H:i:s");
    	$question->save();
        if($type == 3 && $userInfo->user_expert == 1){
            $echo('专家不能回复普通用户！');
            exit;
        }
    	if($type == 1){
    		$questionModel = new QuestionAnswer();
    		$questionModel->answer_floor = $floor->answer_floor+1;
    		$questionModel->answer_content = base64_encode(serialize($content));
    		$questionModel->user_id = $userId;
    		$questionModel->question_id = $questionId;
    		$questionModel->answer_state = 1;
    		$questionModel->type = $userInfo->user_expert ? 2 : 1;
    		$questionModel->answer_pics=json_encode($picArr);
    		if($questionModel->save()){
    			$echo("回复成功！",true);
    		}
    	}else if($type==3) {
            $answerInfo = QuestionAnswer::findFirst($answerId);
            $questionModel = new QuestionAnswer();
            $answerUser = UserBase::findFirst($answerInfo->user_id);
            $questionModel->answer_floor = $floor->answer_floor + 1;
            $questionModel->answer_content = base64_encode(serialize($content));
            $questionModel->user_id = $userId;
            $questionModel->question_id = $questionId;
            $questionModel->answer_state = 1;
            $questionModel->type = $userInfo->user_expert ? 2 : 1;
            $questionModel->answer_pics = json_encode($picArr);
            $questionModel->original_content = base64_encode(serialize($answerUser->user_nickname . "：" . unserialize(base64_decode($answerInfo->answer_content))));

            if ($questionModel->save()) {
                $echo('回复成功！', true);
            }
        }elseif($type == 5) {//回复专家
            $questionInfo = Question::findFirst("question_id = {$questionId}");
            if($userId != $questionInfo->user_id){
                $echo('楼主才能回复！');
                exit;
            }
            $answerCommentmodel = new QuestionAnswerComments();
            $answerCommentmodel->question_id = $questionId;
            $answerCommentmodel->answer_id = $answerId;
            $answerCommentmodel->user_id = $userId;
            $answerCommentmodel->to_user_id = $toUserid;
            $answerCommentmodel->pics = json_encode($picArr);
            $answerCommentmodel->content = base64_encode(serialize($content));
            $answerCommentmodel->add_time = date("Y-m-d H:i:s");
            if ($answerCommentmodel->save()) {
                $echo('回复成功！', true);
            }
        }elseif($type == 6) {//回复楼主
            $answerInfo = QuestionAnswer::findFirst("answer_id = {$answerId}");
            if($userId != $answerInfo->user_id){
                $echo('专家才能回复！');
                exit;
            }
            $answerCommentmodel = new QuestionAnswerComments();
            $answerCommentmodel->question_id = $questionId;
            $answerCommentmodel->answer_id = $answerId;
            $answerCommentmodel->user_id = $userId;
            $answerCommentmodel->to_user_id = $toUserid;
            $answerCommentmodel->pics = json_encode($picArr);
            $answerCommentmodel->content = base64_encode(serialize($content));
            $answerCommentmodel->add_time = date("Y-m-d H:i:s");
            if ($answerCommentmodel->save()) {
                $echo('回复成功！', true);
            }

    	}else{
    		$echo('参数错误！');
    	}	
    }
    /**
     * 删除回复
     * @date: 2016-1-16 
     * @author: miaoyu
     */
    public function deleteanswerAction(){
    	$this->view->disable();
    	$echo = function($msg, $state=false){
    		echo '<script type="text/javascript">';
    		echo 'parent.formResult("' . $msg . '", ' . ($state ? 1 : 0) . ')';
    		echo '</script>';
    	};
    	$req = $this->request;
    	$answerId = intval($req->getQuery('id',null,0));
    	if($answerId<0){
    		$echo("参数错误！");
    		return;
    	}
    	$answerInfo=QuestionAnswer::findFirst($answerId);
    	if(!$answerInfo){
    		$echo('参数错误！');
    		return;
    	}
    	$answerInfo->answer_state = -1;
    	if($answerInfo->save()){
    	    //删除成功 更新回复数量
    	    Question::updateAnswerNum($answerInfo->question_id);
    		$echo("删除成功！",1);
    	}else{
    		$echo("删除失败！");
    	}
    }
    /**
     * 删除楼主回复
     * @date: 2016-1-19 
     * @author: miaoyu
     */
    public function delAction(){
    	$req = $this->request;
    	$id = $req->getQuery('id',null,0);
    	$qid = $req->getQuery('qid',null,0);
    	if($id<0){
    		echo "ID不存在";
    		exit;
    	}
    	$query = QuestionAnswerComments::findFirst($id);
    	if(!$query){
    		echo "ID不存在";
    		exit;
    	}
    	if($query->delete()){
    		echo "<script>location.href='/manage/questionmanage/info?id=".$qid."'</script>";
    	}else{
    		echo "<script>alert('error'),location.href='/manage/questionmanage/info?id=".$id."'</script>";
    	}
    }


    /**
     * 搜索用户
     */
    public function searchuserAction()
    {
        $req = $this->request;
        $userName = $req->getPost('search_user',null,'');
        $list = UserBase::query()->columns(['user_nickname','user_id'])->where("user_nickname like :user_name: and is_manage = 1")->bind(['user_name'=>'%'.$userName.'%'])->execute()->toArray();
        $arr = [
            'list'=>$list
        ];
        echo json_encode($arr);
    }




}